<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋对战平台 - 游戏大厅</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1e3a8a',      // 深蓝主色调
                        secondary: '#f97316',    // 橙色辅助色
                        board: '#e6b89c',        // 棋盘色
                        dark: '#111827',         // 深色背景
                        light: '#f3f4f6',        // 浅色背景
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .board-pattern {
                background-image: linear-gradient(rgba(30, 58, 138, 0.05) 1px, transparent 1px),
                                 linear-gradient(90deg, rgba(30, 58, 138, 0.05) 1px, transparent 1px);
                background-size: 20px 20px;
            }
            .btn-pulse {
                animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            @keyframes pulse {
                0%, 100% {
                    opacity: 1;
                }
                50% {
                    opacity: 0.7;
                }
            }
            .slide-in {
                animation: slideIn 0.5s ease-out forwards;
            }
            @keyframes slideIn {
                from {
                    transform: translateY(20px);
                    opacity: 0;
                }
                to {
                    transform: translateY(0);
                    opacity: 1;
                }
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            }
            .mobile-menu {
                transform: translateX(100%);
                transition: transform 0.3s ease-in-out;
            }
            .mobile-menu.active {
                transform: translateX(0);
            }
            .menu-backdrop {
                opacity: 0;
                visibility: hidden;
                transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
            }
            .menu-backdrop.active {
                opacity: 0.5;
                visibility: visible;
            }
            .scroll-indicator {
                height: 3px;
                background-color: theme('colors.secondary');
                width: 0%;
                position: fixed;
                top: 0;
                left: 0;
                z-index: 50;
                transition: width 0.1s ease;
            }
        }
    </style>
</head>

<body class="bg-gray-50 board-pattern min-h-screen flex flex-col">
    <!-- 滚动进度指示器 -->
    <div class="scroll-indicator" id="scrollIndicator"></div>

    <!-- 移动端菜单 -->
    <div class="mobile-menu fixed top-0 right-0 h-full w-64 bg-white shadow-xl z-50 overflow-y-auto">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-lg">菜单</h3>
            <button id="closeMenu" class="text-gray-500 hover:text-gray-700">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-4 space-y-4">
            <a href="#" class="block py-2 px-4 hover:bg-gray-100 rounded-lg transition-colors">
                <i class="fa fa-rules mr-2 text-primary"></i>游戏规则
            </a>
            <a href="#" class="block py-2 px-4 hover:bg-gray-100 rounded-lg transition-colors">
                <i class="fa fa-history mr-2 text-primary"></i>历史战绩
            </a>
            <a href="#" class="block py-2 px-4 hover:bg-gray-100 rounded-lg transition-colors">
                <i class="fa fa-crown mr-2 text-primary"></i>排行榜
            </a>
            <a href="#" class="block py-2 px-4 hover:bg-gray-100 rounded-lg transition-colors">
                <i class="fa fa-user-circle mr-2 text-primary"></i>个人资料
            </a>
            <a href="#" class="block py-2 px-4 hover:bg-gray-100 rounded-lg transition-colors">
                <i class="fa fa-cog mr-2 text-primary"></i>设置
            </a>
            <div class="border-t pt-4 mt-4">
                <a href="#" class="block py-2 px-4 text-red-500 hover:bg-red-50 rounded-lg transition-colors">
                    <i class="fa fa-sign-out mr-2"></i>退出登录
                </a>
            </div>
        </div>
    </div>

    <!-- 菜单背景遮罩 -->
    <div class="menu-backdrop fixed inset-0 bg-black z-40"></div>

    <!-- 导航栏 -->
    <nav class="bg-primary text-white shadow-lg relative z-30">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-gamepad text-2xl text-secondary"></i>
                <h1 class="text-xl md:text-2xl font-bold">五子棋对战平台</h1>
            </div>
            <div class="flex items-center space-x-4">
                <a href="#" class="hidden md:block hover:text-secondary transition-colors">
                    <i class="fa fa-rules mr-1"></i>游戏规则
                </a>
                <a href="#" class="hover:text-secondary transition-colors">
                    <i class="fa fa-sign-out mr-1"></i>退出
                </a>
                <button id="menuButton" class="md:hidden text-white hover:text-secondary">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8 md:py-12">
        <div class="grid grid-cols-1 gap-8">
            <!-- 左侧：用户信息卡片 -->
            <div>
                <div class="bg-white rounded-xl shadow-md p-6 card-hover slide-in" style="animation-delay: 0.1s">
                    <div class="text-center mb-4">
                        <div class="inline-block p-1 bg-primary rounded-full mb-3">
                            <i class="fa fa-user-circle text-4xl text-white"></i>
                        </div>
                        <h2 class="text-xl font-bold text-gray-800" id="username-display">加载中...</h2>
                    </div>

                    <div class="space-y-4 mt-6">
                        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-600"><i class="fa fa-trophy text-yellow-500 mr-2"></i>当前积分</span>
                            <span class="text-xl font-bold text-primary" id="score-display">--</span>
                        </div>

                        <div class="grid grid-cols-2 gap-3">
                            <div class="p-3 bg-gray-50 rounded-lg text-center">
                                <span class="block text-gray-600 text-sm">比赛场次</span>
                                <span class="block text-lg font-bold text-primary" id="total-count">--</span>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-lg text-center">
                                <span class="block text-gray-600 text-sm">获胜场次</span>
                                <span class="block text-lg font-bold text-secondary" id="win-count">--</span>
                            </div>
                        </div>

                        <div class="pt-3 border-t border-gray-100">
                            <div class="flex justify-between text-sm text-gray-600">
                                <span>胜率</span>
                                <span id="win-rate" class="font-medium">--</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2 mt-2">
                                <div id="win-rate-bar" class="bg-secondary h-2 rounded-full" style="width: 0%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 中间：匹配区域 -->
            <div>
                <div class="w-full bg-white rounded-xl shadow-lg p-6 md:p-8 text-center slide-in"
                    style="animation-delay: 0.2s">
                    <div class="mb-6">
                        <h2 class="text-2xl font-bold text-gray-800 mb-2">寻找对手</h2>
                        <p class="text-gray-500" id="match-status">点击下方按钮开始匹配对手</p>
                    </div>

                    <div class="flex justify-center my-6 md:my-8">
                        <div class="relative w-28 h-28 md:w-32 md:h-32">
                            <div class="absolute inset-0 rounded-full border-4 border-primary/20"></div>
                            <div class="absolute inset-2 rounded-full border-4 border-primary/40"></div>
                            <div
                                class="absolute inset-4 rounded-full border-4 border-primary/60 flex items-center justify-center">
                                <i class="fa fa-users text-3xl text-primary"></i>
                            </div>
                        </div>
                    </div>

                    <button id="match-button"
                        class="w-full py-3 md:py-4 px-6 bg-secondary hover:bg-secondary/90 text-white rounded-lg font-bold text-lg shadow-md hover:shadow-lg transition-all transform hover:-translate-y-1 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-opacity-50">
                        开始匹配
                    </button>

                    <div class="mt-4 text-sm text-gray-500 hidden" id="searching-indicator">
                        <i class="fa fa-spinner fa-spin mr-1"></i>正在搜索对手... 可随时取消
                    </div>
                </div>
            </div>

            <!-- 右侧：排行榜 -->
            <div>
                <div class="bg-white rounded-xl shadow-md p-6 card-hover slide-in" style="animation-delay: 0.3s">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold text-gray-800 flex items-center">
                            <i class="fa fa-star text-yellow-500 mr-2"></i>排行榜
                        </h2>
                        <span class="text-sm bg-primary/10 text-primary px-3 py-1 rounded-full">本月</span>
                    </div>

                    <div class="space-y-4" id="ranking-list">
                        <!-- 排行榜项将通过JS动态生成 -->
                        <div class="animate-pulse">
                            <div class="h-10 bg-gray-200 rounded mb-4"></div>
                            <div class="h-10 bg-gray-200 rounded mb-4"></div>
                            <div class="h-10 bg-gray-200 rounded"></div>
                        </div>
                    </div>

                    <a href="#"
                        class="block text-center mt-6 text-primary hover:text-primary/80 transition-colors text-sm">
                        查看完整排行榜 <i class="fa fa-angle-right ml-1"></i>
                    </a>
                </div>
            </div>
        </div>

        <!-- 最近战绩 -->
        <div class="mt-8 slide-in" style="animation-delay: 0.4s">
            <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                <i class="fa fa-history text-primary mr-2"></i>最近战绩
            </h2>
            <div class="bg-white rounded-xl shadow-md overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th
                                    class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    对手</th>
                                <th
                                    class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    结果</th>
                                <th
                                    class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    时间</th>
                                <th
                                    class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    积分变化</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="recent-games">
                            <!-- 战绩数据将通过JS动态生成 -->
                            <tr class="animate-pulse">
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="h-5 bg-gray-200 rounded w-32"></div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="h-5 bg-gray-200 rounded w-20"></div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="h-5 bg-gray-200 rounded w-32"></div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="h-5 bg-gray-200 rounded w-20"></div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white/70 py-6 mt-8">
        <div class="container mx-auto px-4 text-center text-sm">
            <p>© 2023 五子棋对战平台 - 享受策略博弈的乐趣</p>
            <div class="mt-2 space-x-4">
                <a href="#" class="hover:text-white transition-colors">关于我们</a>
                <a href="#" class="hover:text-white transition-colors">游戏规则</a>
                <a href="#" class="hover:text-white transition-colors">联系客服</a>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        var ws_url = "ws://" + location.host + "/hall";
        var ws_hdl = null;
        var button_flag = "stop"; // 匹配状态标识：stop-未匹配，start-匹配中

        // 页面卸载前关闭WebSocket连接
        window.onbeforeunload = function () {
            if (ws_hdl) {
                ws_hdl.close();
            }
        }

        // 移动端菜单控制
        const menuButton = document.getElementById('menuButton');
        const closeMenu = document.getElementById('closeMenu');
        const mobileMenu = document.querySelector('.mobile-menu');
        const menuBackdrop = document.querySelector('.menu-backdrop');

        menuButton.addEventListener('click', () => {
            mobileMenu.classList.add('active');
            menuBackdrop.classList.add('active');
            document.body.style.overflow = 'hidden';
        });

        function hideMenu() {
            mobileMenu.classList.remove('active');
            menuBackdrop.classList.remove('active');
            document.body.style.overflow = '';
        }

        closeMenu.addEventListener('click', hideMenu);
        menuBackdrop.addEventListener('click', hideMenu);

        // 滚动进度条
        window.addEventListener('scroll', () => {
            const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
            const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
            const scrolled = (winScroll / height) * 100;
            document.getElementById("scrollIndicator").style.width = scrolled + "%";
        });

        // 匹配按钮点击事件
        var be = document.getElementById("match-button");
        be.onclick = function () {
            if (!ws_hdl || ws_hdl.readyState !== WebSocket.OPEN) {
                showNotification("连接尚未准备好，请稍候", "warning");
                return;
            }

            if (button_flag === "stop") {
                // 发送开始匹配请求
                var req_json = { optype: "match_start" };
                ws_hdl.send(JSON.stringify(req_json));
            } else {
                // 发送停止匹配请求
                var req_json = { optype: "match_stop" };
                ws_hdl.send(JSON.stringify(req_json));
            }
        }

        // 获取用户信息并初始化WebSocket
        function get_user_info() {
            $.ajax({
                url: "/info",
                type: "get",
                success: function (res) {
                    // 更新用户信息显示
                    document.getElementById("username-display").textContent = res.username;
                    document.getElementById("score-display").textContent = res.score;
                    document.getElementById("total-count").textContent = res.total_count;
                    document.getElementById("win-count").textContent = res.win_count;

                    // 计算胜率
                    const winRate = res.total_count > 0 ? Math.round((res.win_count / res.total_count) * 100) : 0;
                    document.getElementById("win-rate").textContent = `${winRate}%`;
                    document.getElementById("win-rate-bar").style.width = `${winRate}%`;

                    // 初始化WebSocket连接
                    initWebSocket();

                    // 加载排行榜数据
                    loadRankingData();

                    // 加载最近战绩
                    loadRecentGames();
                },
                error: function (xhr) {
                    showNotification("获取用户信息失败", "error");
                    setTimeout(() => {
                        location.replace("/login.html");
                    }, 1500);
                }
            });
        }

        // 初始化WebSocket
        function initWebSocket() {
            if (ws_hdl) {
                ws_hdl.close();
            }

            ws_hdl = new WebSocket(ws_url);

            ws_hdl.onopen = function () {
                console.log("WebSocket连接已建立");
                showNotification("已连接到游戏服务器", "success");
            };

            ws_hdl.onclose = function (event) {
                if (event.reason) {
                    // 根据提示词显示不同提示
                    alert(`系统提示：${event.reason}`);
                    // 例如：跳转到登录页
                    if (event.reason.includes("账号在其他地方登录")) {
                        window.location.href = "/index.html"; // 跳回登录页
                    }else{
                        console.log("WebSocket连接已关闭");
                        showNotification("与服务器的连接已断开", "warning");
                    }
                }


                // 重置匹配状态
                if (button_flag === "start") {
                    updateMatchButton("stop");
                }
            };

            ws_hdl.onerror = function (error) {
                console.error("WebSocket错误:", error);
                showNotification("连接发生错误", "error");
            };

            ws_hdl.onmessage = function (evt) {
                try {
                    var rsp_json = JSON.parse(evt.data);

                    if (!rsp_json.result) {
                        showNotification(rsp_json.msg || "操作失败", "error");
                        if (rsp_json.need_login) {
                            setTimeout(() => {
                                location.replace("/login.html");
                            }, 1500);
                        }
                        return;
                    }

                    switch (rsp_json.optype) {
                        case "hall_ready":
                            showNotification("游戏大厅连接成功", "success");
                            break;

                        case "match_success":
                            showNotification("匹配成功，正在进入游戏房间...", "success");
                            setTimeout(() => {
                                location.replace("/game_room.html");
                            }, 1000);
                            break;

                        case "match_start":
                            updateMatchButton("start");
                            showNotification("开始寻找对手", "info");
                            break;

                        case "match_stop":
                            updateMatchButton("stop");
                            showNotification("已取消匹配", "info");
                            break;

                        case "match_notify":
                            // 匹配过程中的通知，如"已找到1名玩家"
                            document.getElementById("match-status").textContent = rsp_json.msg || "正在匹配对手...";
                            break;
                    }
                } catch (e) {
                    console.error("解析WebSocket消息失败:", e);
                    showNotification("接收消息格式错误", "error");
                }
            };
        }

        // 更新匹配按钮状态
        function updateMatchButton(state) {
            const button = document.getElementById("match-button");
            const statusText = document.getElementById("match-status");
            const indicator = document.getElementById("searching-indicator");

            if (state === "start") {
                button_flag = "start";
                button.textContent = "取消匹配";
                button.classList.remove("bg-secondary", "hover:bg-secondary/90");
                button.classList.add("bg-gray-600", "hover:bg-gray-700", "btn-pulse");
                statusText.textContent = "正在搜索合适的对手";
                indicator.classList.remove("hidden");
            } else {
                button_flag = "stop";
                button.textContent = "开始匹配";
                button.classList.remove("bg-gray-600", "hover:bg-gray-700", "btn-pulse");
                button.classList.add("bg-secondary", "hover:bg-secondary/90");
                statusText.textContent = "点击下方按钮开始匹配对手";
                indicator.classList.add("hidden");
            }
        }

        // 加载排行榜数据
        function loadRankingData() {
            // 模拟排行榜数据，实际项目中应从服务器获取
            const rankingData = [
                { rank: 1, username: "棋圣", score: 2850, winRate: 89 },
                { rank: 2, username: "弈者", score: 2720, winRate: 82 },
                { rank: 3, username: "黑白子", score: 2680, winRate: 79 },
                { rank: 4, username: "落子无悔", score: 2550, winRate: 75 },
                { rank: 5, username: "手谈", score: 2480, winRate: 72 }
            ];

            const rankingList = document.getElementById("ranking-list");
            rankingList.innerHTML = "";

            rankingData.forEach(user => {
                const item = document.createElement("div");
                item.className = "flex items-center justify-between p-2 hover:bg-gray-50 rounded-lg transition-colors";

                // 排名样式：前三名有特殊颜色
                let rankClass = "w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center font-bold text-gray-600";
                if (user.rank === 1) rankClass = "w-8 h-8 rounded-full bg-yellow-100 flex items-center justify-center font-bold text-yellow-600";
                else if (user.rank === 2) rankClass = "w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center font-bold text-gray-500";
                else if (user.rank === 3) rankClass = "w-8 h-8 rounded-full bg-amber-200 flex items-center justify-center font-bold text-amber-700";

                item.innerHTML = `
                    <div class="flex items-center">
                        <div class="${rankClass}">${user.rank}</div>
                        <span class="ml-3 font-medium">${user.username}</span>
                    </div>
                    <div class="text-right">
                        <div class="text-primary font-bold">${user.score}分</div>
                        <div class="text-xs text-gray-500">胜率 ${user.winRate}%</div>
                    </div>
                `;

                rankingList.appendChild(item);
            });
        }

        // 加载最近战绩
        function loadRecentGames() {
            // 模拟最近战绩数据，实际项目中应从服务器获取
            const gamesData = [
                { opponent: "风之子", result: "胜利", time: "今天 14:35", scoreChange: "+15" },
                { opponent: "石中火", result: "失败", time: "昨天 20:12", scoreChange: "-10" },
                { opponent: "林间客", result: "胜利", time: "昨天 16:47", scoreChange: "+12" }
            ];

            const gamesContainer = document.getElementById("recent-games");
            gamesContainer.innerHTML = "";

            gamesData.forEach(game => {
                const row = document.createElement("tr");

                // 胜利/失败样式
                let resultClass = game.result === "胜利" ? "text-green-600 bg-green-50" : "text-red-600 bg-red-50";
                let scoreClass = game.result === "胜利" ? "text-green-600" : "text-red-600";

                row.innerHTML = `
                    <td class="px-4 py-3 whitespace-nowrap">
                        <div class="flex items-center">
                            <i class="fa fa-user-o mr-2 text-gray-400"></i>
                            <span>${game.opponent}</span>
                        </div>
                    </td>
                    <td class="px-4 py-3 whitespace-nowrap">
                        <span class="px-2 py-1 text-xs font-medium rounded-full ${resultClass}">${game.result}</span>
                    </td>
                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">${game.time}</td>
                    <td class="px-4 py-3 whitespace-nowrap text-sm font-medium ${scoreClass}">${game.scoreChange}</td>
                `;

                gamesContainer.appendChild(row);
            });
        }

        // 显示通知消息
        function showNotification(message, type = "info") {
            // 创建通知元素
            const notification = document.createElement("div");
            notification.className = `fixed top-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 slide-in flex items-center`;

            // 根据类型设置样式
            let icon, bgColor;
            switch (type) {
                case "success":
                    icon = "fa-check-circle";
                    bgColor = "bg-green-50 text-green-800 border-l-4 border-green-500";
                    break;
                case "error":
                    icon = "fa-exclamation-circle";
                    bgColor = "bg-red-50 text-red-800 border-l-4 border-red-500";
                    break;
                case "warning":
                    icon = "fa-exclamation-triangle";
                    bgColor = "bg-yellow-50 text-yellow-800 border-l-4 border-yellow-500";
                    break;
                default:
                    icon = "fa-info-circle";
                    bgColor = "bg-blue-50 text-blue-800 border-l-4 border-blue-500";
            }

            notification.classList.add(...bgColor.split(' '));
            notification.innerHTML = `<i class="fa ${icon} mr-3"></i><span>${message}</span>`;

            // 添加到页面
            document.body.appendChild(notification);

            // 3秒后自动移除
            setTimeout(() => {
                notification.style.opacity = "0";
                notification.style.transform = "translateX(20px)";
                notification.style.transition = "opacity 0.3s, transform 0.3s";

                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }

        // 页面加载完成后获取用户信息
        $(document).ready(function () {
            get_user_info();
        });
    </script>
</body>

</html>